package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    //新增菜品
    @Transactional  //涉及到多张表的操作,开启事务
    @PostMapping
    public R<String> addDish(@RequestBody DishDto dishDto) {
        //log.info("DishDto接收到的数据:{}",dishDto.toString());
        //将dishDto中的Dish和DishFlavor对象的数据分别保存到Dish表和Dish_flavor表中
        List<DishFlavor> flavors = dishDto.getFlavors();
        log.info("flavors:{}", flavors.toString());
        //数据转移大转小
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDto, dish);
        //保存菜品数据
        boolean save = dishService.save(dish);
        //如果保存成功,dishFlavor中的dishId需要从dish中获取
        if (save) {
            Long dishId = dish.getId();
            log.info("id:{}", dishId);
            //获取dishId
            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
                log.info("flavor:{}", flavor);
            });
            //保存dishFlavor
            dishFlavorService.saveBatch(flavors);
        }

        log.info("dish====:{}", dish);
        String key ="dish"+dish.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("保存成功");
    }

    //菜品界面分页查询
    @GetMapping("/page")
    public R<Page<DishDto>> page(int page, int pageSize, String name) {
        log.info("page:{},pageSize:{}", page, pageSize);
        //创建分页构建器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //创建条件构建器
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        //去除空白字符,name非空判断,模糊查询
        String dname = StringUtils.trim(name);
        qw.like(StringUtils.isNotEmpty(dname), Dish::getName, dname);
        qw.orderByDesc(Dish::getSort);
        //查询
        dishService.page(pageInfo, qw);

        //赋值除Records的部分
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> dishDtoList = new ArrayList<>();

        records.forEach(record -> {
            //赋值
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record, dishDto);
            log.info("dishDto:{}", dishDto);
            //查询
            Long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            //赋值CategoryName
            dishDto.setCategoryName(categoryName);
            //收集
            dishDtoList.add(dishDto);
        });
        //赋值
        dishDtoPage.setRecords(dishDtoList);
        log.info("dishDtoList:{}", dishDtoList);
        return R.success(dishDtoPage);

    }

    //修改菜单.根据菜品id
    @GetMapping("{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = new DishDto();
        Dish dish = dishService.getById(id);
        //赋值
        BeanUtils.copyProperties(dish, dishDto);
        log.info("dishDto:{}", dishDto);
        //查询菜品对应的菜品分类
        Long categoryId = dish.getCategoryId();
        Category category = categoryService.getById(categoryId);
        //赋值
        dishDto.setCategoryName(category.getName());
        //查询菜品对应的口味
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(qw);
        //赋值
        dishDto.setFlavors(list);

        //清理缓存
        String key="dish"+dish.getCategoryId()+"_1";
        redisTemplate.delete(key);

        //响应
        return R.success(dishDto);
    }

    //修改菜品
    @Transactional
    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dishDto) {
        log.info("dishDto:{}", dishDto);
        //更新dish表
        dishService.updateById(dishDto);
        //更新dish_flavor表,先根据dishId删除,再保存
        Long dishId = dishDto.getId();
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, dishId);
        //删除
        dishFlavorService.remove(qw);
        //保存
        List<DishFlavor> flavors = dishDto.getFlavors();
        log.info("flavors:{}", flavors.toString());
        //前端响应的新增部分Flavor数据没有dish_id,所以先给dishId赋值
        flavors.forEach(flavor -> {
            flavor.setDishId(dishId);
        });
        dishFlavorService.saveBatch(flavors);

        return R.success("修改成功");

    }

    //停售/起售(批量)
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status, String ids) {
        log.info("ids:{},status:{}", ids, status);
        Dish dish = new Dish();
        dish.setStatus(status);
        String[] split = ids.split(",");
        List<String> idList = Arrays.asList(split);
        UpdateWrapper<Dish> qw = new UpdateWrapper<>();
        qw.in("id", idList);
        dishService.update(dish, qw);

        return R.success("停售成功");
    }

    //(批量)删除
    @DeleteMapping
    public R<String> deleteBatch(String ids) {
        log.info("ids:{}", ids);
        //获取idList集合
        String[] split = ids.split(",");
        List<String> idList = Arrays.asList(split);
        //批量删除
        dishService.removeBatchByIds(idList);
        return R.success("删除成功");
    }

    //根据套餐id查询对应的菜品
    @GetMapping("/list")
    public R<List<DishDto>> getDishList(Dish dish) {
        //log.info("dish:{}", dish);
        List<DishDto> dishDtoList = null;

        log.info("dishDtoList:{}", dishDtoList);
        String key ="dish"+dish.getCategoryId()+"_"+dish.getStatus();
        dishDtoList =(List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null) {
            return R.success(dishDtoList);
        }
        ArrayList<DishDto> dishDtoResultList = new ArrayList<>();
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(dish.getCategoryId()!=null,Dish::getCategoryId, dish.getCategoryId());
        qw.eq(dish.getStatus()!=null,Dish::getStatus,dish.getStatus());
        List<Dish> dishList = dishService.list(qw);

        for (Dish dishOne : dishList) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dishOne,dishDto);

            //根据dishId查dish_flavor
            Long dishId = dishOne.getId();
            LambdaQueryWrapper<DishFlavor> dfqw = new LambdaQueryWrapper<>();
            dfqw.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> flavorsList = dishFlavorService.list(dfqw);

            dishDto.setFlavors(flavorsList);
            dishDtoResultList.add(dishDto);
        }


        redisTemplate.opsForValue().set(key,dishDtoResultList,30, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
